<?php

namespace app\client\services;

use app\admin\model\CustomerLoginLogModel;
use app\admin\model\CustomerModel;

class TiktokPromoteService
{
    protected static $dev=false;

    protected static function returnBaseUrl(){
        if(self::$dev){
            return 'https://taskapi-fat.doutuimao.net';
        }else{
            return 'https://taskapi.doutuimao.net';
        }
    }

    /**
     * 抖音退管订单推送
     * @param $customerId 用户id 用来计算sharecode
     * @param $orderNo 订单号
     * @param $payMoney 支付金额/重量
     * @param $create_time 订单创建时间
     * @return mixed|\stdClass
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function pushOrder($sharecode,$orderNo,$payMoney,$create_time){
        $url=self::returnBaseUrl().'/mini/income/synccreateorder';
        $data=[
            'appid'=>TiktokService::AppID,
            'sharecode'=>$sharecode,
            'order_no'=>$orderNo,
            'pay_money'=>(string)$payMoney,
            'pay_time'=>(string)time(),
            'order_time'=>(string)strtotime($create_time),
            'sub_id'=>'1',
            'order_status'=>'1'
        ];
        $res=post($url,$data,['sign:'.self::getSign($data)]);
        return json_decode($res);
    }

    public static function pushUvData(){
        $date=date('Y-m-d');
        $list=CustomerLoginLogModel::countGroupByShareCode($date);
        foreach ($list as $item) {
            $url = self::returnBaseUrl() . '/mini/income/synccreatevisitor';
            $data = [
                'appid' => TiktokService::AppID,
                'sharecode' => $item['sharecode'],
                'visitors' => (string)$item['count'],
                'times' => $date,
                'platform'=>'1',
                'sub_id'=>'1',
            ];
            $res=post($url,$data,['sign:'.self::getSign($data)]);
            print_r($res."\n");
        }
    }

    protected static function getSign($data){
        $key = '5Eh7xBIFBcHdqHba4vPUb3jOLZ6jNSzq';
        ksort($data);//对请求参数按键名进行排序
        $body_str = json_encode($data);//将数组生成json字符串
        $sign = md5($body_str.$key);//json字符串拼接$key值，生成md5值
        return  $sign;
    }

}
